import cv2 as cv 
import numpy as np 
import os 

def to_point(points):
    for point in points:
        point = point[...,:4]
        point[...,:2] -= point[...,2:] / 2
        point[...,2:] += point[...,:2]
    return points

def iou(gt, anchor):
    return 

def draw_rect(img, points, color, show_each=False):
    cv.namedWindow("tmp", 0)
    for point in points:
        x1, y1, x2, y2 = point[:4] 
        x1 = max(int(x1 * w), 0)
        y1 = max(int(y1 * h), 0)
        x2 = min(int(x2 * w), w)
        y2 = min(int(y2 * h), h)       
        if show_each:
            tmp = img.copy()
            cv.rectangle(tmp, (x1, y1), (x2, y2), color)
            cv.imshow("tmp", tmp)
            cv.waitKey(0)
        else:
            cv.rectangle(img, (x1, y1), (x2, y2), color)


from utils.boxes import create_prior_boxes
import math
# def get_configuration_file():
#     # make sure the s_min a dynamic scales, the article said the min is 0.1, s_min / 2
#     s0_min_scale = 1.5 # 2
#     s_min = 0.5
#     s_max = 0.8
#     m = 3
#     scales = [math.ceil((s_min + (s_max - s_min) * (k-1) / (m - 1)) * w) for k in range(1,m + 2)] # (0.2 - 0.4), s = s_min + (s_max - s_min) * (k-1) / (m - 1), m=3 , (0.2 0.3 0.4)
#     min_sizes = [math.ceil(w * s_min / s0_min_scale)] + scales[:-1]
#     max_sizes = scales
#     steps = [8, 16, 32, 64]
    
#     configuration = {'feature_map_sizes': [(w // s, w // s) for s in steps],  #(24, 32), (12, 16), (6, 8), (3, 4)
#                                                                                  # 3 2 2 3
#                      'image_size': [w, h],
#                      'steps': steps,
#                      'min_sizes': min_sizes,
#                      'max_sizes': max_sizes,
#                      'aspect_ratios': [[2], [], [], [2]],
#                      'square_msk': [[True, False], True, True, [True, False]],   # small, big
#                      'rectangle_msk': [[True, True], False, False, [True, True]],   # [w>h, h>w]
#                      'variance': [0.1, 0.2]}
#     return configuration

if __name__ == "__main__":
    w, h = 64, 64
    # anchors = np.load("./prior_boxes.npy")
    from train import get_configuration_file
    anchors = (create_prior_boxes(configuration=get_configuration_file()))

    people_pos = np.load("./class_dataset/train_face_pos.npy")
    imgs = np.load("./class_dataset/train_img.npy")

    people_pos = to_point(people_pos)
    anchors = to_point(anchors)

    cv.namedWindow("img", 0)

    for img, poses in zip(imgs, people_pos):
        draw_rect(img, poses, (0, 255, 0))
        draw_rect(img, anchors, (0, 0, 255), show_each=True)
        cv.imshow("img", img)
        cv.waitKey(0)
